﻿using Dapper;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class WareHousingController : ControllerBase
    {
        private readonly MyDbContext myDbContext;

        private readonly pro_warehousingService _pro_warehousingService;

        private readonly pro_warehousing_fromService _pro_warehousing_fromService;

        public WareHousingController(MyDbContext myDbContext, pro_warehousingService pro_warehousingService, pro_warehousing_fromService pro_warehousing_fromService) 
        {
            this.myDbContext = myDbContext;
            _pro_warehousingService = pro_warehousingService;
            _pro_warehousing_fromService = pro_warehousing_fromService;
        }

        /// <summary>
        /// 生产订单入库查询
        /// </summary>
        /// <returns></returns>  
        [HttpGet]
        public async Task<List<pro_warehousing>> WareIdext()
        {

            return await _pro_warehousingService.Query();
        }
        /// <summary>
        ///生产订单入库添加
        /// </summary>
        /// <returns></returns> 
        [HttpPost]   
        public async Task<IActionResult> WareAdd([FromBody] pro_warehousing warehousing)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateWarehouseCode(maxCodeNumber);

            warehousing.pw_number = newCode;
            if (ModelState.IsValid)
            {
                int result = await _pro_warehousingService.Add(warehousing);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.pro_warehousing
               .Where(w => w.pw_number.StartsWith("SCRK"))
               .Select(w => w.pw_number.Substring(5)) // 修改为从第三个字符开始截取
               .OrderByDescending(code => code)
               .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);

            // 生成新的编码数字部
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了9999，则重置为0001
            if (newCodeNumber > 9999)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }

        // 生成新的编码
        private string GenerateWarehouseCode(int codeNumber)
        {
            // 返回完整的编码，包括前缀 "GYS" 和数字部分
            string code = "SCRK" + codeNumber.ToString("D2");

            // 如果编码超过了列的最大长度，截取适合长度
            int maxLength = 10; // 假设列的最大长度为10，根据实际情况修改
            if (code.Length > maxLength)
            {
                code = code.Substring(0, maxLength);
            }

            return code;
        }
        /// <summary>
        ///生产订单入库修改
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> WareUpdate(pro_warehousing warehousing)
        {

         
            if (ModelState.IsValid)
            {
                warehousing.pro_warehousing_from = null;
                int result = await _pro_warehousingService.Update(warehousing);
                if (result > 0)
                {
                    return Ok("修改成功！");

                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        /// <summary>
        /// 生产订单入库删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{pw_id}")]
        public async Task<string> WareDelete(int pw_id)
        {
            var model = await myDbContext.pro_warehousing
                .Include(m => m.pro_warehousing_from)
                .FirstOrDefaultAsync(m => m.pw_id == pw_id);

            if (model == null || model.IsDeleted == true)
            {
                return "未找到对应的数据";
            }

            // 检查是否存在未被删除的 bs_Model_From 数据
            var undeletedFroms = model.pro_warehousing_from.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }

            // 逻辑删除 bs_model 数据
            model.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }

        /// <summary>
        /// 生产订单入库分页
        /// </summary>
        /// <returns></returns> 

        [HttpGet]
        public ActionResult<FenYe<pro_warehousing>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pw_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pro_warehousing "); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pro_warehousing>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pro_warehousing> fenYe = new FenYe<pro_warehousing>()
                {
                    warehousing = result,
                    Rows = row,
                };

                if (fenYe.warehousing.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }


        /// <summary>
        /// 生产订单入库子查询
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public async Task<List<pro_warehousing_from>> WaregFrom()
        {
            return await _pro_warehousing_fromService.Query();
        }

        /// <summary>
        /// 生产订单子入库添加
        /// </summary>
        /// <returns></returns> 

        [HttpPost]
        public async Task<IActionResult> WaregAdd(pro_warehousing_from warehousingFrom)
        {
            if (ModelState.IsValid)
            {

                int result = await _pro_warehousing_fromService.Add(warehousingFrom);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        /// <summary>
        ///生产订单入库子修改
        /// </summary>
        /// <returns></returns> 

        [HttpPut]
        public async Task<IActionResult> WaregUpdate(pro_warehousing_from warehousingFrom)
        {
            if (ModelState.IsValid)
            {
                int result = await _pro_warehousing_fromService.Update(warehousingFrom);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }

        }


        /// <summary>
        /// 生产订单入库子删除
        /// </summary>
        /// <returns></returns>

        [HttpDelete("{wf_id}")]
        public async Task<IActionResult> WaregDelete(int wf_id)
        {
            int result = await _pro_warehousing_fromService.Delete(wf_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }


        /// <summary>
        ///子分页查询
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public ActionResult<FenYe<pro_warehousing_from>> WarehFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "wf_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pro_warehousing_from"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pro_warehousing_from>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pro_warehousing_from> fenYe = new FenYe<pro_warehousing_from>()
                {
                    warehousingFrom = result,
                    Rows = row,
                };

                if (fenYe.warehousingFrom.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }





        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="pw_id"></param>
        /// <returns></returns>
        [HttpPost("{pw_id}")]
        public async Task<IActionResult> AuditSalesReturn(int pw_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOut = await myDbContext.pro_warehousing
                .Include(so => so.pro_warehousing_from) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.pw_id == pw_id);

            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            if (salesOut == null || salesOut.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            // 检查从表sal_Orders是否有数据
            if (!salesOut.pro_warehousing_from.Any() || salesOut.pro_warehousing_from.All(order => order.IsDeleted))

            {
                return BadRequest("从表没有数据，不能进行审核");
            }


            try
            {
                // 审核销售订单
                salesOut.AuditStatus = true;
                salesOut.pw_state = "1";
                salesOut.pw_warehouse = '2';


                // 同时更新关联的销售订单状态
                var salesOrder = await myDbContext.pro_orders
                    .FirstOrDefaultAsync(so => so.po_number == salesOut.pw_number);
                if (salesOrder != null )
                {
                    salesOrder.po_state = salesOut.pw_state; // 更新销售入库状态
                    salesOrder.po_warehouse = salesOut.pw_warehouse;
                }


                if (salesOut.pw_warehouse == '2')
                {
                    foreach (var returnItem in salesOut.pro_warehousing_from)
                    {
                        var invStorage = new inv_Storage
                        {
                            ow_id = 0,
                            ow_item_name = returnItem.wf_sing_model,
                            ow_specification = salesOut.pw_number,
                            ow_item_attributes = "产品",
                            ow_unit = "箱",
                            ow_quantity = returnItem.wf_storage,
                            ow_warehouse = returnItem.wf_inbound_warehouse,
                            ow_operators = salesOut.pw_operators,
                            ow_storage_date = DateTime.Now,
                            ow_audit = false,
                            IsDeleted = false,
                            ow_type = "生产入库",
                            ow_create_by = "Admin",
                            ow_create_time = DateTime.Now,
                            ow_update_by = "Admin",
                            ow_update_time = DateTime.Now,
                        };
                        myDbContext.inv_Storage.Add(invStorage);
                    }
                }

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，入库成功");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }
    }
}
